package com.wbk.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wbk.dao.CheckGroupDao;
import com.wbk.entity.PageResult;
import com.wbk.entity.QueryPageBean;
import com.wbk.pojo.CheckGroup;
import com.wbk.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupDao checkGroupDao;

    /**
     * 新增检查组
     * @param checkGroup
     * @param checkitemIds
     */
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        //新增检查组
        checkGroupDao.add(checkGroup);
        //关联检查项多对多关系
        Integer checkGroupId = checkGroup.getId();
        this.setCheckGroupIdAndCheckItemId(checkitemIds,checkGroupId);
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckGroup> page = checkGroupDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<CheckGroup> checkGroupList = page.getResult();
        return new PageResult(total,checkGroupList);
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupDao.findById(id);
    }

    @Override
    public List<Integer> findCheckItemIdByCheckGroupId(Integer id) {
        return checkGroupDao.findCheckItemIdByCheckGroupId(id);
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //更新检查组信息
        checkGroupDao.edit(checkGroup);
        //删除检查组关联检查项信息
        checkGroupDao.deleteAssociation(checkGroup.getId());
        //重新写入关联检查项信息
        this.setCheckGroupIdAndCheckItemId(checkitemIds,checkGroup.getId());
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }

    //重新写入关联检查项信息
    public void setCheckGroupIdAndCheckItemId(Integer[] checkitemIds,Integer checkGroupId){
        Map<String,Integer> map=new HashMap<>();
        if (checkitemIds!=null&&checkitemIds.length>0){
            for (Integer checkitemId:checkitemIds){
                map.put("checkitemId",checkitemId);
                map.put("checkGroupId",checkGroupId);
                checkGroupDao.setCheckGroupIdAndCheckItemId(map);
            }
        }
    }
}
